﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EvinceUI
{
    public class Authorize
    {
        public class AuthorizeOrRedirectAttribute : AuthorizeAttribute
        {
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                base.OnAuthorization(filterContext);

                if (filterContext.Result is HttpUnauthorizedResult)
                {
                    var scheme = filterContext.RequestContext.HttpContext.Request.Url.Scheme;
                    var host = filterContext.RequestContext.HttpContext.Request.Headers["Host"];
                    var path = filterContext.RequestContext.HttpContext.Request.RawUrl;
                    var returnUrl = scheme + @"://" + host + path;

                    filterContext.Result =
                            new RedirectResult("~/Account/Login?returnUrl=" + HttpUtility.UrlEncode(returnUrl));
                }
            }
        }
        public class SessionExpireAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                base.OnActionExecuted(filterContext);
            }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (filterContext.HttpContext.Session != null)
                {
                    if (filterContext.HttpContext.Session.IsNewSession)
                    {
                        var sessionCookie = filterContext.HttpContext.Request.Headers["Cookie"];
                        if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                        {
                            var scheme = filterContext.RequestContext.HttpContext.Request.Url.Scheme;
                            var host = filterContext.RequestContext.HttpContext.Request.Headers["Host"];
                            var path = filterContext.RequestContext.HttpContext.Request.RawUrl;
                            var returnUrl = scheme + @"://" + host + path;

                            filterContext.Result =
                                    new RedirectResult("~/Account/Login?returnUrl=" + HttpUtility.UrlEncode(returnUrl));
                        }
                    }
                }
            }
        }

    }
}